package org.arch_learn.orm_starter.utils;

import org.arch_learn.flashboot.ConnectionManager;
import org.arch_learn.orm_starter.po.Configuration;
import org.arch_learn.orm_starter.sqlSession.DefaultSqlSession;
import org.arch_learn.orm_starter.sqlSession.DefaultSqlSessionFactory;

import java.sql.Connection;
import java.sql.SQLException;

public class DefaultConnectionManager implements ConnectionManager {
    public static DefaultSqlSessionFactory defaultSqlSessionFactory;

    public void setDefaultSqlSessionFactory(DefaultSqlSessionFactory defaultSqlSessionFactory) {
        this.defaultSqlSessionFactory = defaultSqlSessionFactory;
    }

    public DefaultConnectionManager(DefaultSqlSessionFactory defaultSqlSessionFactory) {
        this.defaultSqlSessionFactory = defaultSqlSessionFactory;
    }

    public static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    @Override
    public Connection getCurrentConnection() {
        Connection connection = threadLocal.get();
        try {
            if (connection == null) {
                DefaultSqlSession defaultSqlSession = (DefaultSqlSession) defaultSqlSessionFactory.openSession();
                Configuration configuration = defaultSqlSession.getConfiguration();
                threadLocal.set(configuration.getDataSource().getConnection());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return threadLocal.get();
    }

    public static Connection getConnection() {
        Connection connection = threadLocal.get();
        try {
            if (connection == null) {
                DefaultSqlSession defaultSqlSession = (DefaultSqlSession) defaultSqlSessionFactory.openSession();
                Configuration configuration = defaultSqlSession.getConfiguration();
                threadLocal.set(configuration.getDataSource().getConnection());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return threadLocal.get();
    }
}
